/**
 * 
 */
package cc.rico.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author JiWo 2016年6月23日
 *
 */
@Controller
@RequestMapping(value="/login")
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	
	@RequestMapping
	public String login() {
		return "login/login";
	}
	
	@RequestMapping(value="/authenticate", method=RequestMethod.POST)
	public String authenticate(String username, String password) {
		logger.info("##LoginController.authenticate");
		
		Subject currentUser = SecurityUtils.getSubject();
		if(currentUser.isAuthenticated()) {
			logger.info("user[{}] already log in...", currentUser.getPrincipal());
		}
		
		try {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password, false);
			currentUser.login(token);
		
			return "home/home";
			
		} catch ( UnknownAccountException uae ) {
	    	logger.error(uae.getMessage(), uae);
	    } catch ( IncorrectCredentialsException ice ) {
	        logger.error(ice.getMessage(), ice);
	    } catch ( LockedAccountException lae ) {
	    	logger.error(lae.getMessage(), lae);
	    } catch ( AuthenticationException ae ) {
	    	logger.error(ae.getMessage(), ae);
	    }
		
		return "error/unauthorized";
	}
	
	@RequestMapping(value="/home")
	public String home() {
		return "home";
	}
	
	@RequestMapping(value="/unauthorized")
	public String unauthorized() {
		return "unauthorized";
	}
}
